package com.example.HaiDLaobackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.HaiDLaobackend.common.ApiResponse;
import com.example.HaiDLaobackend.entity.CouponEntity;
import com.example.HaiDLaobackend.entity.UserCouponEntity;
import com.example.HaiDLaobackend.service.CouponService;
import com.example.HaiDLaobackend.service.UserCouponService;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class CouponController {

    private final CouponService couponService;
    private final UserCouponService userCouponService;

    public CouponController(CouponService couponService, UserCouponService userCouponService) {
        this.couponService = couponService;
        this.userCouponService = userCouponService;
    }

    @GetMapping("/api/users/coupons")
    public ApiResponse<List<Map<String, Object>>> userCoupons(@RequestAttribute(value = "currentUserId", required = false) Long currentUserId) {
        if (currentUserId == null) return ApiResponse.error(401, "未登录");
        List<UserCouponEntity> userCoupons = userCouponService.list(new LambdaQueryWrapper<UserCouponEntity>()
                .eq(UserCouponEntity::getUserId, currentUserId)
                .eq(UserCouponEntity::getStatus, 0)
                .orderByDesc(UserCouponEntity::getAcquiredAt));
        Map<Long, Long> countMap = userCoupons.stream().collect(Collectors.groupingBy(UserCouponEntity::getCouponId, Collectors.counting()));
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map.Entry<Long, Long> entry : countMap.entrySet()) {
            CouponEntity coupon = couponService.getById(entry.getKey());
            if (coupon == null) continue;
            Map<String, Object> dto = new HashMap<>();
            dto.put("id", coupon.getId());
            dto.put("name", coupon.getName());
            dto.put("description", coupon.getDescription());
            dto.put("discountAmount", coupon.getDiscountAmount());
            dto.put("thresholdAmount", coupon.getThresholdAmount());
            dto.put("startTime", coupon.getStartTime());
            dto.put("endTime", coupon.getEndTime());
            dto.put("count", entry.getValue());
            result.add(dto);
        }
        return ApiResponse.ok(result);
    }

    @PostMapping("/api/coupons/checkin")
    public ApiResponse<CouponEntity> checkin(@RequestAttribute(value = "currentUserId", required = false) Long currentUserId) {
        if (currentUserId == null) return ApiResponse.error(401, "未登录");
        // 简化：发放一个“签到立减券”（若不存在则创建），每次签到送一张未使用券
        CouponEntity sign = couponService.getOne(new LambdaQueryWrapper<CouponEntity>()
                .eq(CouponEntity::getName, "签到立减券"));
        if (sign == null) {
            sign = new CouponEntity();
            sign.setName("签到立减券");
            sign.setDescription("每日签到奖励");
            sign.setDiscountAmount(new java.math.BigDecimal("10"));
            sign.setThresholdAmount(new java.math.BigDecimal("0"));
            sign.setStartTime(LocalDateTime.now());
            sign.setEndTime(LocalDateTime.now().plusDays(30));
            sign.setStatus(1);
            couponService.save(sign);
        }
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
        long todayCount = userCouponService.count(new LambdaQueryWrapper<UserCouponEntity>()
                .eq(UserCouponEntity::getUserId, currentUserId)
                .eq(UserCouponEntity::getCouponId, sign.getId())
                .ge(UserCouponEntity::getAcquiredAt, todayStart));
        if (todayCount > 0) {
            return ApiResponse.error(400, "今日已签到领取");
        }
        UserCouponEntity uc = new UserCouponEntity();
        uc.setUserId(currentUserId);
        uc.setCouponId(sign.getId());
        uc.setStatus(0);
        uc.setAcquiredAt(LocalDateTime.now());
        userCouponService.save(uc);
        return ApiResponse.ok(sign);
    }
    
    @GetMapping("/api/coupons/available")
    public ApiResponse<List<Map<String, Object>>> getAvailableCoupons(
            @RequestAttribute(value = "currentUserId", required = false) Long currentUserId,
            @RequestParam(required = false) String orderAmount) {
        if (currentUserId == null) return ApiResponse.error(401, "未登录");
        
        // 获取用户所有未使用的优惠券
        List<UserCouponEntity> userCoupons = userCouponService.list(new LambdaQueryWrapper<UserCouponEntity>()
                .eq(UserCouponEntity::getUserId, currentUserId)
                .eq(UserCouponEntity::getStatus, 0)
                .orderByDesc(UserCouponEntity::getAcquiredAt));
        
        List<Map<String, Object>> result = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        
        for (UserCouponEntity uc : userCoupons) {
            CouponEntity coupon = couponService.getById(uc.getCouponId());
            if (coupon == null || coupon.getStatus() == null || coupon.getStatus() == 0) {
                continue;
            }
            
            // 检查优惠券是否在有效期内
            if (coupon.getStartTime() != null && now.isBefore(coupon.getStartTime())) {
                continue;
            }
            if (coupon.getEndTime() != null && now.isAfter(coupon.getEndTime())) {
                continue;
            }
            
            // 如果提供了订单金额，检查是否满足使用门槛
            if (orderAmount != null && !orderAmount.isEmpty() && coupon.getThresholdAmount() != null) {
                try {
                    BigDecimal amount = new BigDecimal(orderAmount);
                    if (amount.compareTo(coupon.getThresholdAmount()) < 0) {
                        continue;
                    }
                } catch (Exception e) {
                    // 解析失败，跳过门槛检查
                }
            }
            
            Map<String, Object> dto = new HashMap<>();
            dto.put("id", coupon.getId());
            dto.put("userCouponId", uc.getId());
            dto.put("name", coupon.getName());
            dto.put("description", coupon.getDescription());
            dto.put("discountAmount", coupon.getDiscountAmount());
            dto.put("thresholdAmount", coupon.getThresholdAmount());
            dto.put("startTime", coupon.getStartTime());
            dto.put("endTime", coupon.getEndTime());
            result.add(dto);
        }
        
        return ApiResponse.ok(result);
    }
}


